import axios from 'axios'
import { ElLoading } from 'element-plus'

const isServer = process.server
let loadingInstance = null
let startLoadingTime = null

function closeLoading() {
    if (!isServer) {
        if (loadingInstance) {
            loadingInstance.close()
            loadingInstance = null
        }
        if (startLoadingTime) {
            clearInterval(startLoadingTime)
            startLoadingTime = null
        }
    }

}

function startLoadingHandler() {
    if (!isServer) {
        if (!loadingInstance) {
            startLoadingTime = setInterval(() => {
                loadingInstance = ElLoading.service({ fullscreen: true })
            }, 300)
        }
    }
}

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
const service = axios.create({
    // axios中请求配置有baseURL选项，表示请求URL公共部分
    baseURL: process.env.BASE_URL,
    // 超时
    timeout: 180 * 1000,
})

service.interceptors.request.use((config) => {
    config.headers['token'] = ''

    // 开启加载
    startLoadingHandler()

    // get请求映射params参数
    if (config.method === 'get' && config.params) {
        let url = config.url + '?'
        for (const propName of Object.keys(config.params)) {
            const value = config.params[propName]
            var part = encodeURIComponent(propName) + '='
            if (value !== null && typeof value !== 'undefined') {
                if (typeof value === 'object') {
                    for (const key of Object.keys(value)) {
                        let params = propName + '[' + key + ']'
                        var subPart = encodeURIComponent(params) + '='
                        url += subPart + encodeURIComponent(value[key]) + '&'
                    }
                } else {
                    url += part + encodeURIComponent(value) + '&'
                }
            }
        }
        url = url.slice(0, -1)
        config.params = {}
        config.url = url
    }
    return config
}, error => {
    closeLoading()
    Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use((res) => {
    // 关闭加载
    closeLoading()
    return res.data
}, error => {
    // 关闭加载
    closeLoading()
    console.log('接口返回异常', error)
})

export default service
